package cn.xiongxf.basic.controller;

import cn.xiongxf.basic.util.AjaxResult;
import cn.xiongxf.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传
 * 下载 = 不需要
 * 查看 = 路径
 * 删除
 * 更新 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    // @RequestPart对复杂表单项的处理，默认name = "file",与上传文件的name属性值一致
   /* @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            String filePath =  FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath);  // 返回上传后的路径
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("上传失败!"+e.getMessage());
        }
    }*/

    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file) {
        AjaxResult result = AjaxResult.me();
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件扩展名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            // 上传文件并返回文件路径
            String uploadPath = FastDfsUtils.upload(file.getBytes(), substring);
            // 返回上传路径
            result.setResultObj(uploadPath);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("上传失败");
            return result;
        }
    }

    /**
     * 参数：完整路径 /group1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            // 去掉最前面的/
            String pathTemp = path.substring(1);  // group1/xxxxx/yyyy
            // 获取组名
            String groupName =  pathTemp.substring(0, pathTemp.indexOf("/"));  // group1
            // 获取文件名
            String remotePath = pathTemp.substring(pathTemp.indexOf("/")+1);  // xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);
            // 删除文件
            FastDfsUtils.delete(groupName, remotePath);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败!"+e.getMessage());
        }
    }
}